package me.leiusual.sharing.ui.base

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.view.View
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.LinearLayout
import dagger.android.support.DaggerFragment

/**
 * author: leiusual
 * create on: 2019-07-27
 * description:
 */
abstract class AbstractWebViewFragment : DaggerFragment() {

  abstract val layoutWebView: LinearLayout

  protected val webView: WebView by lazy {
    WebView(requireContext().applicationContext)
  }

  @SuppressLint("SetJavaScriptEnabled")
  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT)
    layoutWebView.addView(webView, params)

    val webSettings = webView.settings

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
    }

    // 设置支持javascript脚本
    webSettings.javaScriptEnabled = true

    // 设置此属性，可任意比例缩放
    webSettings.useWideViewPort = true

    // 设置不出现缩放工具
    webSettings.builtInZoomControls = false

    // 设置不可以缩放
    webSettings.setSupportZoom(false)
    webSettings.displayZoomControls = false

    // 自适应屏幕
    webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN

    // 自适应 屏幕大小界面
    webSettings.loadWithOverviewMode = true

    // 设置不用系统浏览器打开，直接显示在当前webView
    webView.webViewClient = object : WebViewClient() {

      override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
        view?.loadUrl(url)
        return true
      }
    }
  }

  override fun onResume() {
    super.onResume()

    webView.onResume()
  }

  override fun onPause() {
    super.onPause()

    webView.onPause()
  }

  override fun onDestroyView() {
    super.onDestroyView()

    webView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
    webView.clearHistory()
    layoutWebView.removeView(webView)
    webView.destroy()
  }
}